<div class="row">
    <div class="col-lg-12">
        <section class="panel">
            <header class="panel-heading">
                回款列表
            </header>
            <div class="panel-body">
                <div class="row">
                    <div class="col-lg-6 col-md-12">
                        <form class="form-inline" role="form" onsubmit="return false;">
                            <div class="form-group">
                                <select id="ReceivablesType" class="form-control">
                                    <option value='0' selected>全部</option>
                                    <option value='1'>我提交的回款</option>
                                    <option value='2'>我審核的回款</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <input type="text" class="form-control" id="Keyword" placeholder="客户名称/回款编号">
                            </div>
                            <button id="SearchBtn" type="button" class="btn btn-success">搜索</button>
                        </form>
                    </div>
                    <div class="col-lg-6 col-md-12" style="text-align: right">
                        <button id="Add" class="btn btn-danger"><i class=" icon-plus"></i> 新建回款</button>
                        <button id="Export" class="btn"><i class="icon-cloud-download"></i> 导出</button>
                    </div>
                </div>
                <div class="row">

                    <div class="col-lg-12">
                        <table id="DataList" lay-filter="DataList" class="table"></table>

                        <!-- 回款数据表格 - 回款方式模板 -->
                        <script type="text/html" id="TplType">
                            {{# var TypeName = mb_GetTypeName(d.Type); }}
                            {{ TypeName }}
                        </script>

                        <!-- 回款数据表格 - 状态模板 -->
                        <script type="text/html" id="TplStatus">
                            {{# var Status = mb_GetStatusName(d.Status); }}
                            <span style="color: {{Status.Color}}">{{Status.Name}}</span>
                        </script>

                        <!-- 回款数据表格 - 头部工具栏 -->
                        <script type="text/html" id="HeadToolBar_0">
                            <div class="layui-btn-container">
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="delete">
                                    <i class="icon-trash"></i> 删除选中
                                </button>
                            </div>
                        </script>

                        <script type="text/html" id="HeadToolBar_2">
                            <div class="layui-btn-container">
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="delete">
                                    <i class="icon-trash"></i> 删除选中
                                </button>
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="pass">
                                    <i class="icon-ok"></i> 审核通过
                                </button>
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="nopass">
                                    <i class="icon-remove"></i> 审核不通过
                                </button>
                            </div>
                        </script>

                        <script type="text/html" id="ToolBar_0">
                            {{#
                                var ShowMoreType = 0;
                                if(d.UserID == {$UserID}){
                                    if(d.AuditorID == {$UserID}){
                                        if(d.Status == 1 || d.Status == 2){
                                            ShowMoreType = 3;
                                        } else {
                                            ShowMoreType = 0;
                                        }
                                    } else {
                                        if(d.Status == 1 || d.Status == 2){
                                            ShowMoreType = 1;
                                        } else {
                                            ShowMoreType = 0;
                                        }
                                    }
                                } else {
                                    if(d.AuditorID == {$UserID}){
                                        if(d.Status == 1 || d.Status == 2){
                                            ShowMoreType = 2;
                                        } else {
                                            ShowMoreType = 0;
                                        }
                                    } else {
                                        ShowMoreType = 0;
                                    }
                                }
                            }}
                            {{# if(ShowMoreType == 0) { }}
                            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="check">查看 </a>
                            {{# }else if(ShowMoreType == 1){ }}
                            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑 </a>
                            {{# }else if(ShowMoreType == 2){ }}
                            <a class="layui-btn layui-btn-primary layui-btn-xs xsg-more-check" lay-event="more">
                                更多<i class="layui-icon layui-icon-down layui-font-12"></i>
                            </a>
                            {{# }else if(ShowMoreType == 3){ }}
                            <a class="layui-btn layui-btn-primary layui-btn-xs xsg-more-edit-check" lay-event="more">
                                更多<i class="layui-icon layui-icon-down layui-font-12"></i>
                            </a>
                            {{# } }}
                            {{# if((d.UserID == {$UserID} || d.AuditorID == {$UserID}) && (d.Status == 1 || d.Status == 2)) { }}
                            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del">删除 </a>
                            {{# } }}
                        </script>
                    </div>
                </div>


            </div>
        </section>

    </div>
</div>

<!-- 新增回款 -->
<div id="AddDialog" style="display: none">
    <form class="layui-form form-horizontal" role="form" lay-filter="AddReceivables">

        <div class="row" style="margin: 15px 15px;">
            <div class="form-group">
                <label class="col-md-3 control-label">回款编号</label>
                <div class="col-md-9">
                    <input id="Number" type="text" class="form-control" placeholder="根据编号规则自动生成，支持手动输入">
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">客户<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <select id="ClientID" name="ClientID" lay-verify="required" lay-search="" class="form-control">
                        <option value="0"></option>
                        <?php
                            foreach($Clients as $Key => $Val){
                                $tID = $Val['ID'];
                                $tName = $Val['Name'];
                                $tContact = $Val['Contacts'];
                                echo "<option value='$tID'>$tName - $tContact</option>";
                            }
                        ?>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">合同<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <select id="ContractID" name="ContractID" lay-verify="required" lay-search="" class="form-control">
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">回款日期<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <input id="Date" type="date" class="form-control" lay-verify="required" placeholder="">
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">回款方式<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <select id="Type" name="Type" lay-verify="required" lay-search="" class="form-control">
                        <option value="0">请选择</option>
                        <option value="1">支票</option><!-- 回款方式（1：支票，2：現金，3：邮政汇款，4：电汇，5：网上转账，6：支付宝，7：微信支付，8：其他） -->
                        <option value="2">现金</option>
                        <option value="3">邮政汇款</option>
                        <option value="4">电汇</option>
                        <option value="5">网上转账</option>
                        <option value="6">支付宝</option>
                        <option value="7">微信支付</option>
                        <option value="8">其他</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">回款金额<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <input id="Money" type="Money" class="form-control" lay-verify="required" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">合同电子版</label>
                <div class="col-md-9">
                    <div class="layui-upload">
                        <button type="button" class="btn btn-primary" id="UploadBtn">选择文件</button>
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            预览图：
                            <div class="layui-upload-list" id="PreviewImages"></div>
                        </blockquote>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">审核人</label>
                <div class="col-md-9">
                    <select id="AuditorID" name="AuditorID" lay-verify="required" lay-search="" class="form-control">
                        <?php
                        foreach($Users as $Key => $Val){
                            $tID = $Val['ID'];
                            $tName = $Val['Nick'];
                            $tDepartment = $Val['DepartmentName'];
                            echo "<option value='$tID'>$tDepartment - $tName</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">备注</label>
                <div class="col-md-9">
                    <textarea id="Remark" class="form-control"></textarea>
                </div>
            </div>
        </div>
    </form>

</div>
<!-- 查看回款 -->
<div id="CheckDialog" style="display: none">
    <form class="layui-form form-horizontal" role="form" lay-filter="AddReceivables">

        <div class="row" style="margin: 15px 15px;">
            <div class="form-group">
                <label class="col-md-3 control-label">回款编号</label>
                <div class="col-md-9">
                    <span id="CheckNumber" class="form-control"></span>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">客户<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <span id="CheckClient" class="form-control"></span>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">合同<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <span id="CheckContract" class="form-control"></span>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">回款日期<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <span id="CheckDate" class="form-control"></span>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">回款方式<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <span id="CheckType" class="form-control"></span>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">回款金额<span class="xsg-span-required">*</span></label>
                <div class="col-md-9">
                    <span id="CheckMoney" class="form-control"></span>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">合同电子版</label>
                <div class="col-md-9">
                    <div class="layui-upload">
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            预览图：
                            <div class="layui-upload-list" id="CheckPreviewImages"></div>
                        </blockquote>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">审核人</label>
                <div class="col-md-9">
                    <span id="CheckAuditor" class="form-control"></span>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">备注</label>
                <div class="col-md-9">
                    <textarea id="CheckRemark" class="form-control" disabled style="background-color: #ffffff"></textarea>
                </div>
            </div>
        </div>
    </form>

</div>

<script>
    layui.use(['table', 'layer', 'jquery', 'upload', 'form', 'dropdown'], function () {
        var table = layui.table,
            layer = layui.layer,
            upload = layui.upload,
            form = layui.form,
            $ = layui.$,
            dropdown = layui.dropdown,
            FileUrls = [],
            ReceivableData = null;


        //选择对应合同分类
        $('#ReceivablesType').bind('change', function () {
            var Type = $('#ReceivablesType').val();
            var ToolBar = '#HeadToolBar_0';
            if(Type == 2) ToolBar = '#HeadToolBar_2'
            console.log(ToolBar);

            table.reload('DataList', {
                toolbar: ToolBar, //开启头部工具栏，并为其绑定左侧模板
                where: {
                    Type: Type,
                    Keyword: $('#Keyword').val(),

                }
            });
        });

        //搜寻按钮按下
        $('#SearchBtn').bind('click', function () {
            table.reload('DataList', {
                where: {
                    Keyword: $('#Keyword').val(),
                    Type: $('#ReceivablesType').val()
                }
            });
        });

        //关键字输入框回车按下
        $('#Keyword').bind('keypress', function (event) {
            if (event.keyCode == "13") {
                //需要处理的事情
                var Keyword = $('#Search').val();
                table.reload('DataList', {
                    where: {
                        Keyword: Keyword
                    }
                });
            }
        });

        //新增回款按下
        $('#Add').bind('click', function () {
            $('#Number').val('');
            $('#ClientID').val(0);
            $('#Date').val('');
            $('#Type').val(0);
            $('#Money').val(0);
            $('#PreviewImages').html('');
            $('#AuditorID').val(0);
            $('#Remark').val('');

            var dialogWidth = '650px';
            if (document.documentElement.scrollWidth < 500) {
                //手機版
                dialogWidth = '350px';
            }
            layer.open({
                type: 1,
                title: '新增回款',
                area: [dialogWidth, '700px'],
                content: $('#AddDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['保存', '取消'],
                yes: function (index, layero) {
                    var Number = $('#Number').val();
                    var ClientID = $('#ClientID').val();
                    var ContractID = $('#ContractID').val();
                    var Date = $('#Date').val();
                    var Type = $('#Type').val();
                    var Money = $('#Money').val();
                    var AuditorID = $('#AuditorID').val();
                    var Remark = $('#Remark').val();

                    if (ClientID == 0) {
                        layer.msg('请选择客户', {icon: 2});
                        return;
                    }
                    if (ContractID == 0) {
                        layer.msg('请选择合同', {icon: 2});
                        return;
                    }
                    if (Date == 0) {
                        layer.msg('请选择回款日期', {icon: 2});
                        return;
                    }
                    if (Type == 0) {
                        layer.msg('请选择回款方式', {icon: 2});
                        return;
                    }
                    if (Money == 0 || Money == '') {
                        layer.msg('请输入回款金额', {icon: 2});
                        return;
                    }
                    if (AuditorID == 0) {
                        layer.msg('请选择审核人', {icon: 2});
                        return;
                    }

                    var fields = {
                        ReceivablesID: 0,
                        Number: Number,
                        ClientID: ClientID,
                        ContractID: ContractID,
                        Date: Date,
                        Type: Type,
                        Money: Money,
                        AuditorID: AuditorID,
                        FileUrls: JSON.stringify(FileUrls),
                        Remark: Remark,
                        Status: 2
                    }

                    global.post('/index.php/user/Receivables/mb_Submit', fields, function (msg) {
                        if (msg['code'] == ErrCode_Normal) {
                            layer.msg('保存成功', {
                                offset: '15px'
                                , icon: 1
                                , time: 1000
                            }, function () {
                                layer.close(index);
                                table.reload('DataList', {
                                    where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                                        Type: $('#ReceivablesType').val(),
                                        Keyword: $('#Keyword').val()
                                    }
                                });
                            });
                            return false;
                        } else {
                            mb_OnMessage(msg);
                            return false;
                        }
                    });
                },
                btn2: function (index, layer0) {
                    console.log('取消按下');
                }
            });
        });

        //导出回款按下
        $('#Export').bind('click',function () {
            console.log('导出按下');
            console.log(table.cache["DataList"]);

            var IDs = '';
            var Data = table.cache["DataList"];
            for (var i = 0; i < Data.length; i++) {
                IDs += Data[i].ID;
                if (i != (Data.length - 1)) IDs += ',';
            }
            var loadIndex = layer.load(2, {shade: [0.15, 'rgba(0,0,0,0.50)']});
            global.post('/index.php/user/Receivables/mb_Export', {
                IDs : IDs
            }, function (msg) {
                layer.close(loadIndex);
                if (msg['code'] == ErrCode_Normal) {
                    layer.msg(msg['msg'], {
                        offset: '15px'
                        , icon: 1
                        , time: 1000
                    }, function () {
                        window.open(msg['data']['url']);
                    });
                } else mb_OnMessage(msg);
            })
        })

        //新增页 - 选择客户后回调
        form.on('select(ClientID)', function (data) {
            mb_ContractSelectsRender(data.value,form);
        });

        //回款数据表
        var tableIns = table.render({
            elem: '#DataList'
            , autoSort: false
            , height: '695'
            , url: '/index.php/user/Receivables/mb_Listing' //数据接口
            , toolbar: '#HeadToolBar_0' //开启头部工具栏，并为其绑定左侧模板
            , page: {
                theme: '#ff6c60'
            }
            ,done:function (res, curr, count) {
                dropdown.render({
                    elem: '.xsg-more-check' //添加普通下拉框
                    ,data: [{
                        title: '查看'
                        ,id: 100
                    },{
                        title: '审核通过'
                        ,id: 101
                    },{
                        title: '审核不通过'
                        ,id: 102
                    }]
                    // ,id: 'demo1'
                    //菜单被点击的事件
                    ,click: function(obj){
                        console.log(obj);
                        if(obj.id == 100){
                            //查看
                            mb_CheckOnClick(layer,ReceivableData);
                        } else if(obj.id == 101){
                            //通过
                            mb_PassOrNoOnClick(ReceivableData.ID,3, layer, table);
                        } else if(obj.id == 102){
                            //不通过
                            mb_PassOrNoOnClick(ReceivableData.ID,4, layer, table);
                        }
                    }
                });
                dropdown.render({
                    elem: '.xsg-more-edit-check' //添加普通下拉框
                    ,data: [{
                        title: '编辑'
                        ,id: 100
                    },{
                        title: '审核通过'
                        ,id: 101
                    },{
                        title: '审核不通过'
                        ,id: 102
                    }]
                    // ,id: 'demo1'
                    //菜单被点击的事件
                    ,click: function(obj){
                        console.log(obj);
                        if(obj.id == 100){
                            //编辑
                            mb_EditOnClick(layer, ReceivableData, form, table);
                        } else if(obj.id == 101){
                            //通过
                            mb_PassOrNoOnClick(ReceivableData.ID,3, layer, table);
                        } else if(obj.id == 102){
                            //不通过
                            mb_PassOrNoOnClick(ReceivableData.ID,4, layer, table);
                        }

                    }
                });
            }
            , where: {
                Type: $('#ContractType').val(),
                Keyword: $('#Keyword').val()
            }
            , limit: 100
            , limits: [100, 200, 300, 400, 500]
            , cols: [[ //表头 總寬度1670
                {type: 'checkbox', fixed: 'left'}
                , {field: 'Number', title: '回款编号', width: 200, fixed: 'left'}
                , {field: 'ClientName', title: '客户名称', width: 200}
                , {field: 'ContractNumber', title: '合同编号'}
                , {field: 'Date', title: '回款日期', sort: true}
                , {field: 'Type', title: '回款方式', sort: true,templet: '#TplType'}
                , {field: 'Money', title: '回款金额', sort: true}
                , {field: 'Remark', title: '备注'}
                , {field: 'UserNick', title: '提交人'}
                , {field: 'AuditorName', title: '审核人'}
                , {field: 'Status', title: '状态',templet: '#TplStatus', sort:true}
                , {title: '編輯', width: 138, align: 'center', toolbar: '#ToolBar_0', fixed: 'right'}
            ]]
        });

        //触发排序事件
        table.on('sort(DataList)', function (obj) { //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            console.log(obj.field); //当前排序的字段名
            console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）

            //尽管我们的 table 自带排序功能，但并没有请求服务端。
            //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
            table.reload('DataList', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    Type: $('#ReceivablesType').val(),
                    Keyword: $('#Keyword').val(),
                    OrderField: obj.field, //排序字段
                    OrderType: obj.type //排序方式
                }
            });
        });

        //监听行工具事件
        table.on('tool(DataList)', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

            if(layEvent === 'check'){
                //查看
                mb_CheckOnClick(layer, data);
            } else if(layEvent === 'edit'){
                //编辑
                mb_EditOnClick(layer, data, form, table);
            } else if(layEvent === 'del'){
                //删除
                if (data.Status == 3) {
                    layer.msg('该回款记录已审核', {icon: 2});
                    return false;
                }
                var fields = {
                    Type: 'Receivables',
                    IDs: data.ID
                };
                global.post('/index.php/user/Event/mb_Delete', fields, function (msg) {
                    if (msg['code'] == ErrCode_Normal) {
                        layer.msg(msg['msg'], {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                        }, function () {
                            // tableIns.reload();
                            obj.del();
                        });
                    } else mb_OnMessage(msg);
                });
            } else if(layEvent === 'more'){
                ReceivableData = data;
            }
        });

        //头工具栏事件
        table.on('toolbar(DataList)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);

            if(obj.event == 'pass' || obj.event == 'nopass' || obj.event == 'delete'){
                if (checkStatus.data.length == 0) {
                    layer.msg('请选择回款记录', {icon: 2});
                    return false
                }
            }

            switch (obj.event) {
                case 'pass':
                    var data = checkStatus.data;
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].Status == 1) {
                            layer.msg('有回款记录为草稿，请先提交', {icon: 2});
                            return false;
                        } else if (data[i].Status == 3 || data.Status == 4) {
                            layer.msg('有回款记录已审核，请重新选择', {icon: 2});
                            return false;
                        }
                        if (data[i].AuditorID != {$UserID}) {
                            layer.msg('有回款记录不是由您审核，请重新选择', {icon: 2});
                            return false;
                        }
                    }
                    for (var i = 0; i < data.length; i++) {

                        var fields = {
                            Type: 'Receivables',
                            Params: JSON.stringify({
                                ID: data[i].ID,
                                Status: 3
                            })
                        }
                        global.post('/index.php/user/Event/mb_Edit', fields, function (msg) {
                            if (msg['code'] == ErrCode_Normal) {

                            } else mb_OnMessage(msg);
                        });
                    }

                    layer.msg('保存成功', {
                        offset: '15px'
                        , icon: 1
                        , time: 1000
                    }, function () {
                        tableIns.reload();
                    });

                    break;
                case 'nopass':
                    var data = checkStatus.data;
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].Status == 1) {
                            layer.msg('有回款记录为草稿，请先提交', {icon: 2});
                            return false;
                        } else if (data[i].Status == 3 || data.Status == 4) {
                            layer.msg('有回款记录已审核，请重新选择', {icon: 2});
                            return false;
                        }
                        if (data[i].AuditorID != {$UserID}) {
                            layer.msg('有回款记录不是由您审核，请重新选择', {icon: 2});
                            return false;
                        }
                    }
                    for (var i = 0; i < data.length; i++) {

                        var fields = {
                            Type: 'Receivables',
                            Params: JSON.stringify({
                                ID: data[i].ID,
                                Status: 4
                            })
                        }
                        global.post('/index.php/user/Event/mb_Edit', fields, function (msg) {
                            if (msg['code'] == ErrCode_Normal) {

                            } else mb_OnMessage(msg);
                        });
                    }
                    layer.msg('保存成功', {
                        offset: '15px'
                        , icon: 1
                        , time: 1000
                    }, function () {
                        tableIns.reload();
                    });
                    break;
                case 'delete':
                    //刪除選中
                    var data = checkStatus.data;
                    var ids = '';
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].Status == 3) {
                            layer.msg('有合同记录已审核，请重新选择', {icon: 2});
                            return false;
                        }
                    }
                    for (var i = 0; i < data.length; i++) {
                        ids += data[i].ID;
                        if (i != data.length - 1) ids += ','
                    }
                    var fields = {
                        Type: 'Receivables',
                        IDs: ids
                    };
                    global.post('/index.php/user/Event/mb_Delete', fields, function (msg) {
                        if (msg['code'] == ErrCode_Normal) {
                            layer.msg(msg['msg'], {
                                offset: '15px'
                                , icon: 1
                                , time: 1000
                            }, function () {
                                tableIns.reload();
                            });
                        } else mb_OnMessage(msg);
                    });
                    break;
                default:
                    break;
            }
        });

        //多图片上传
        upload.render({
            elem: '#UploadBtn'
            , url: '/index.php/Index/Common/UploadImage' //此处配置你自己的上传接口即可
            , multiple: true
            , field: 'Image'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                // obj.preview(function(index, file, result){
                //     $('#PreviewImages').append('<a href="'+result+'" target="_blank"><img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img" style="max-width: 128px;max-height: 128px;"></a>')
                // });
            }
            , done: function (res) {
                //上传完毕
                if (res['code'] == ErrCode_Normal) {
                    var src = res['data']['src'];
                    FileUrls.push(src);
                    $('#PreviewImages').append('<a href="' + src + '" target="_blank"><img src="' + src + '" alt="合同电子版" class="layui-upload-img" style="max-width: 128px;margin: 10px"></a>');
                } else mb_OnMessage(res);
            }
        });
    });

    function mb_GetStatusName(Status) {

        var StatusName = '草稿';//狀態（1：草稿，2：待審核，3：審核通過，4：審核不通過）
        var StatusColor = '#666666';
        if (Status == 2) {
            StatusName = '待审核';
        } else if (Status == 3) {
            StatusName = '审核通过';
            StatusColor = '#78CD51';
        } else if (Status == 4) {
            StatusName = '审核不通过';
            StatusColor = '#ec6459';
        }
        return {Name: StatusName, Color: StatusColor};
    }

    function mb_GetTypeName(Type) {
        //回款方式（1：支票，2：現金，3：邮政汇款，4：电汇，5：网上转账，6：支付宝，7：微信支付，8：其他）
        var TypeName = '支票';
        if(Type == 2){
            TypeName = '现金';
        } else if(Type == 3){
            TypeName = '邮政汇款';
        } else if(Type == 4){
            TypeName = '电汇';
        } else if(Type == 5){
            TypeName = '网上转账';
        } else if(Type == 6){
            TypeName = '支付宝';
        } else if(Type == 7){
            TypeName = '微信支付';
        } else if(Type == 8){
            TypeName = '其他';
        }
        return TypeName;
    }

    function mb_ContractSelectsRender(ClientID, form, SelectID = 0) {
        global.post('/index.php/user/Contract/mb_Listing', {
            Type: 0,
            ClientID: ClientID
        }, function (msg) {
            if (msg['code'] == ErrCode_Normal) {
                $('#ContractID').empty();
                $("#ContractID").append("<option value='0'>请选择</option>");
                for (var i = 0; i < msg['data'].length; i++) {
                    var tData = msg['data'][i];
                    var tID = tData.ID;
                    var tNum = tData.Number;
                    var tName = tData.Name;
                    $("#ContractID").append("<option value='"+tID+"'>"+tNum+" - "+tName+"</option>");
                }
                if (SelectID != 0) $('#ContractID').val(SelectID);
                form.render();

            } else mb_OnMessage(msg);
        });
    }

    function mb_CheckOnClick(layer,data) {
        var dialogWidth = '650px';
        if (document.documentElement.scrollWidth < 500) {
            //手機版
            dialogWidth = '350px';
        }
        //初始化数据
        console.log(data);
        $('#CheckNumber').text(data.Number);
        $('#CheckClient').text(data.ClientName);
        $('#CheckContract').text(data.ContractNumber);
        $('#CheckDate').text(data.Date);
        $('#CheckType').text(mb_GetTypeName(data.Type));
        $('#CheckMoney').text(data.Money);
        $('#CheckPreviewImages').html('');
        var ImageUrls = JSON.parse(data.FileUrls);
        for(var i = 0; i < ImageUrls.length; i++) {
            var src = ImageUrls[i];
            $('#CheckPreviewImages').append('<a href="' + src + '" target="_blank"><img src="' + src + '" alt="合同电子版" class="layui-upload-img" style="max-width: 128px;margin: 10px"></a>');
        }
        $('#CheckAuditor').text(data.AuditorName);
        $('#CheckRemark').text(data.Remark);

        layer.open({
            type: 1,
            title: '查看回款',
            area: [dialogWidth, '700px'],
            content: $('#CheckDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
        });
    }

    function mb_EditOnClick(layer, data, form, table) {
        $('#Number').val(data.Number);
        $('#ClientID').val(data.ClientID);
        mb_ContractSelectsRender(data.ClientID,form,data.ContractID);

        $('#Date').val(data.Date);
        $('#Type').val(data.Type);
        $('#Money').val(data.Money);
        $('#PreviewImages').html('');
        var ImageUrls = JSON.parse(data.FileUrls);
        FileUrls = [];
        for(var i = 0; i < ImageUrls.length; i++) {
            var src = ImageUrls[i];
            FileUrls.push(src);
            $('#PreviewImages').append('<a href="' + src + '" target="_blank"><img src="' + src + '" alt="合同电子版" class="layui-upload-img" style="max-width: 128px;margin: 10px"></a>');
        }
        $('#AuditorID').val(data.AuditorID);
        $('#Remark').val(data.Remark);

        var dialogWidth = '650px';
        if (document.documentElement.scrollWidth < 500) {
            //手機版
            dialogWidth = '350px';
        }
        layer.open({
            type: 1,
            title: '編輯回款',
            area: [dialogWidth, '700px'],
            content: $('#AddDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var Number = $('#Number').val();
                var ClientID = $('#ClientID').val();
                var ContractID = $('#ContractID').val();
                var Date = $('#Date').val();
                var Type = $('#Type').val();
                var Money = $('#Money').val();
                var AuditorID = $('#AuditorID').val();
                var Remark = $('#Remark').val();

                if (ClientID == 0) {
                    layer.msg('请选择客户', {icon: 2});
                    return;
                }
                if (ContractID == 0) {
                    layer.msg('请选择合同', {icon: 2});
                    return;
                }
                if (Date == 0) {
                    layer.msg('请选择回款日期', {icon: 2});
                    return;
                }
                if (Type == 0) {
                    layer.msg('请选择回款方式', {icon: 2});
                    return;
                }
                if (Money == 0 || Money == '') {
                    layer.msg('请输入回款金额', {icon: 2});
                    return;
                }
                if (AuditorID == 0) {
                    layer.msg('请选择审核人', {icon: 2});
                    return;
                }

                var fields = {
                    ReceivablesID: data.ID,
                    Number: Number,
                    ClientID: ClientID,
                    ContractID: ContractID,
                    Date: Date,
                    Type: Type,
                    Money: Money,
                    AuditorID: AuditorID,
                    FileUrls: JSON.stringify(FileUrls),
                    Remark: Remark,
                    Status: 2
                }

                global.post('/index.php/user/Receivables/mb_Submit', fields, function (msg) {
                    if (msg['code'] == ErrCode_Normal) {
                        layer.msg('保存成功', {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                        }, function () {
                            layer.close(index);
                            table.reload('DataList', {
                                where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                                    Type: $('#ReceivablesType').val(),
                                    Keyword: $('#Keyword').val()
                                }
                            });
                        });
                        return false;
                    } else {
                        mb_OnMessage(msg);
                        return false;
                    }
                });
            },
            btn2: function (index, layer0) {
                console.log('取消按下');
            }
        });
        form.render();
    }

    function mb_PassOrNoOnClick(ID, Status, layer, table) {
        var fields = {
            Type: 'Receivables',
            Params: JSON.stringify({
                ID: ID,
                Status: Status
            })
        }
        global.post('/index.php/user/Event/mb_Edit', fields, function (msg) {
            if (msg['code'] == ErrCode_Normal) {
                layer.msg('审核成功', {
                    offset: '15px'
                    , icon: 1
                    , time: 1000
                }, function () {
                    table.reload('DataList', {
                        where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                            Type: $('#ReceivablesType').val(),
                            Keyword: $('#Keyword').val()
                        }
                    });
                });
            } else mb_OnMessage(msg);
        });
    }

</script>
<style>
    .layui-input {
        border-color: #e2e2e4;
        height: 34px;
        border-radius: 4px;
        color: #c2c2c2;
    }

    .xsg-span-required {
        color: red;
        margin: 0 5px;
    }

    .layui-table-tips-c:before {
        position: relative;
        right: 1px;
        top: -3px;
    }
</style>